package com.yao.seckill.web.service.impl;

import com.yao.seckill.core.SeckillResponse;
import com.yao.seckill.web.pojo.SeckillOrder;
import com.yao.seckill.web.mapper.SeckillOrderMapper;
import com.yao.seckill.web.service.ISeckillOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.seckill.web.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaobing
 * @since 2022-08-31
 */
@Service
@Slf4j
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrder> implements ISeckillOrderService, InitializingBean {
    @Autowired
    private RedisUtils redisUtils;

    private ConcurrentHashMap<String,Boolean> map=new ConcurrentHashMap();
    @Autowired
    private RedisTemplate redisTemplate;

    private AtomicInteger count=new AtomicInteger(0);
    @Override
    public SeckillResponse doSeckill(Integer goodsId) {
        String lockKey="goods:"+goodsId;

        if(map.get(lockKey)){
            //如果没库存则直接返回
            return SeckillResponse.error("库存不足");
        }

        Long result = redisTemplate.opsForValue().decrement(lockKey);

        log.info("result={}",result);
        if(result<0){
            map.put(lockKey,true);//库存不足则修改
            return SeckillResponse.error("库存不足");
        }

        count.incrementAndGet();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        return SeckillResponse.success();
    }

    @Override
    public void doClearCache() {

    }

    @Override
    public int getResult() {
        return count.intValue();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        map.put("goods:1",false);//false有库存，true为没有库存
    }
}
